package application.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import application.models.Modwineitems;
import application.models.Modwinewines;

import library.Controller;

/**
 * Servlet implementation class Inventory
 */
public class inventory extends Controller {
	private static final long serialVersionUID = 1L;
    
	@SuppressWarnings("unchecked")
	public void list(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		String name = this.getClass().getSimpleName();
		if(request.getSession().getAttribute("user")!= null) {
			//Prepare Session
			SessionFactory sessionFactory = new Configuration()
				.configure()
				.buildSessionFactory();
			//Start session
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			

			List<Modwineitems> items = (List<Modwineitems>) session.createQuery("from Modwineitems").list();
			request.setAttribute("items", items);
			
			out.flush();
			include(request,response,"/layout/"+name+"/list.jsp");
			
			session.getTransaction().commit();
			session.close();
		}else {
			response.sendRedirect("administrator?op=login");
		}	
	}
	
	public void add(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		String name = this.getClass().getSimpleName();
		if(request.getSession().getAttribute("user")!= null) {
			out.flush();
			request.setAttribute("winery", null);
			include(request,response,"/layout/"+name+"/edit.jsp");
		}else {
			response.sendRedirect("administrator?op=login");
		}
	}
	
	@SuppressWarnings("unchecked")
	public void edit(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		String name = this.getClass().getSimpleName();
		
		if(request.getParameter("id") == null)
			response.sendRedirect(name+"?op=list");
		String type_id = (String) request.getParameter("id");
		
		if(request.getSession().getAttribute("user")!= null) {
			//Prepare Session
			SessionFactory sessionFactory = new Configuration()
				.configure()
				.buildSessionFactory();
			//Start session
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			
			Query sql = session.createQuery("from Modwineitems where item_id =:id");
			List<Modwineitems> items = (List<Modwineitems>) sql.setInteger("id", Integer.parseInt(type_id)).list();
			if(items.isEmpty())
				response.sendRedirect(name+"?op=list");
			else {
				out.flush();
				request.setAttribute("item", (Modwineitems) items.get(0));
				include(request,response,"/layout/"+name+"/edit.jsp");
			}
			
			session.getTransaction().commit();
			session.close();			
		}else {
			response.sendRedirect("administrator?op=login");
		}
	}
	
	@SuppressWarnings("unchecked")
	public void delete(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException {
		String name = this.getClass().getSimpleName();
		String type_id = (String) request.getParameter("id");
		if(request.getSession().getAttribute("user")!= null) {
			//Prepare Session
			SessionFactory sessionFactory = new Configuration()
				.configure()
				.buildSessionFactory();
			//Start session
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			
			Query sql = session.createQuery("from Modwineitems where item_id =:id");
			List<Modwineitems> items = (List<Modwineitems>) sql.setInteger("id", Integer.parseInt(type_id)).list();
			session.delete(items.get(0));
			
			session.getTransaction().commit();
			session.close();
			
			response.sendRedirect(name+"?op=list");
		} else {
			response.sendRedirect("administrator?op=login");
		}
	}
	
	@SuppressWarnings({ "unchecked" })
	public void save(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		try {
			String name = this.getClass().getSimpleName();
			if(request.getSession().getAttribute("user")!= null) {
				//Prepare Session
				SessionFactory sessionFactory = new Configuration()
					.configure()
					.buildSessionFactory();
				//Start session
				Session session = sessionFactory.openSession();
				session.beginTransaction();
				
				Date DateStore = null;
				
				if(request.getParameter("id")!= null){
					String type_id = (String) request.getParameter("id");
					Query sql = session.createQuery("from Modwineitems where item_id =:id");
					
					List<Modwineitems> items = (List<Modwineitems>) sql.setInteger("id", Integer.parseInt(type_id)).list();
					
					if(items.isEmpty()) {
						response.sendRedirect(name+"?op=list");
					} else {
						DateStore = items.get(0).getStoreDate();
						session.delete(items.get(0));
					}
				}
				
				Modwineitems item = new Modwineitems();
				
				Query sql = session.createQuery("from Modwinewines where wine_id =:id");
				List<Modwinewines> wines = (List<Modwinewines>) sql.setInteger("id", Integer.parseInt(request.getParameter("wine"))).list();
				
				if(!wines.isEmpty())
					item.setModwinewines(wines.get(0));
				
				item.setQta(Integer.parseInt(request.getParameter("qta")));
				
				item.setPrice(Float.parseFloat(request.getParameter("price")));
				
				if(DateStore != null)
					item.setStoreDate(DateStore);
				else
					item.setStoreDate(new Date());
				
				session.save(item);
				response.sendRedirect(name+"?op=list");
				
				session.getTransaction().commit();
				session.close();			
			}else {
				response.sendRedirect("administrator?op=login");
			}
		}catch(Exception e){
			PrintWriter x = response.getWriter();
			x.write(e.toString()+":"+e.getLocalizedMessage());
		}
	}
}
